import re

from rest_framework import serializers
from apps.users.models import User


class AdminSerialzier(serializers.ModelSerializer):
    class Meta:
        # 指定模型类
        model = User
        # 指定字段
        fields = '__all__'
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
            },
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
            }
        }

    def validate(self, attrs):
        # 验证手机号格式
        if not re.match('1[3-9]\d{9}', attrs['mobile']):
            raise serializers.ValidationError('手机格式不正确')
        return attrs

    def create(self, validated_data):
        """
            重写ModelSerializer的create方法，实现密码加密的功能
        """
        user = super().create(validated_data)
        # 加密父类中返回的用户，然后对用户密码进行加码
        user.set_password(validated_data['password'])
        user.is_staff = True
        user.save()
        return user

    def update(self, instance, validated_data):
        user = super().update(instance,validated_data)
        # 加密父类中返回的用户，然后对用户密码进行加码
        user.set_password(validated_data['password'])
        user.save()
        return user